package com.aiyige.page.edituserinfo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.User;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.EditUserIntroductionPage)
public class EditUserIntroductionPage extends AppCompatActivity {
    public static final int MAX_INTRODUCTION_LENGTH = 300;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.totalCharNumTv)
    TextView totalCharNumTv;
    @BindView(R.id.charNumTv)
    TextView charNumTv;
    @BindView(R.id.introductionEt)
    EditText introductionEt;
    InputNumFilter inputNumFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_introduction);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setText(R.string.self_introduction);
        totalCharNumTv.setText("/" + MAX_INTRODUCTION_LENGTH);
        charNumTv.setText("0");
        inputNumFilter = new InputNumFilter(MAX_INTRODUCTION_LENGTH);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                charNumTv.setText(num + "");
            }
        });
        introductionEt.setFilters(new InputFilter[]{inputNumFilter});
        introductionEt.setText(AccountUtil.getCurrentUser().getMoreBackup().getIntroduce());
        introductionEt.setSelection(introductionEt.getText().length());
    }

    @OnClick({R.id.titleBackBtn, R.id.confirmBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.confirmBtn:
                new AsyncTask<String, Object, Object>() {
                    LoadingDialog loadingDialog;

                    @Override
                    protected void onPreExecute() {
                        loadingDialog = LoadingDialog.newBuilder().with(EditUserIntroductionPage.this).show();
                    }

                    @Override
                    protected Object doInBackground(String... params) {
                        try {
                            String introduce = params[0];
                            Response<ResponseBody> response = ApiManager.getService().userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder()
                                    .moreBackup(User.MoreBackup.newBuilder().introduce(introduce).build())
                                    .build())
                                    .execute();
                            if (response.code() != ResponseCode.CREATED) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = RetrofitUtil.getResponseBodyAsString(response);
                            User tempUser = JSON.parseObject(json, User.class);
                            User user = AccountUtil.getCurrentUser();
                            user.getMoreBackup().setIntroduce(tempUser.getMoreBackup().getIntroduce());
                            AccountUtil.updateCurrentUser(user);
                            ToastX.show(R.string.edit_user_introduction_success);
                            return null;
                        } catch (Exception e) {
                            return e;
                        }
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        loadingDialog.dismiss();
                        if (o instanceof Exception) {
                            ToastX.show(((Exception) o).getMessage());
                        } else {
                            finish();
                        }
                    }
                }.execute(introductionEt.getText().toString().trim());
                break;
        }
    }
}
